<?php

/**
 * 天虹科技SDK
 * @author chenyun
 */
namespace App\Service\VendorClient\ShopTianhongApi;
use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssLogModel\MicroServiceLog;
use App\Service\HttpServer\Http;

class ShopTianhongApiClient extends BaseService
{
    protected $config = [];
    protected $bid    = null;
    private $account  = 'shopTianhong';
    //接口映射
    protected $routeMap = [
        'updateSkuStock'       => "/stock/updateSkuStock",
        'updateProdStatus'     => "/product/productMarket",
        'findMerchantProduct'  => "/product/findMerchantProduct",
    ];
    public function __construct( $shop = NULL)
    {
        $this->config = @json_decode($shop['extends'], true);
        $this->bid    = $shop['bid'];
    }
    /**
     * 拉取商品列表
     * @param array $param
     */
    public function findMerchantProduct(array $param)
    {
        $_extra = [
            "merchant_id"  => $this->config["merchant_id"],
        ];
        $requestParam = [
            'method' => 'findMerchantProduct',
            'data'   => array_merge($param,$_extra),
        ];
        return $this->execute($requestParam);
    }
    /**
     * SKU 库存单个修改接口
     * @param array $params
     * @return mixed
     */
    public function updateSkuStock(array $param)
    {
        $data = [
            "outer_id"      => $param['outer_id'],
            "quantity"      => $param['quantity'],
            "merchant_id"   => $this->config["merchant_id"],
        ];
        //组装推送上游数据
        $requestParam = [
            'method' => 'updateSkuStock',
            'data'   => $data,
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 商品上下架接口
     * @param array $params
     * @return mixed
     */
    public function updateProdStatus(array $param)
    {
        $data = [
            "prod_id"       => $param['prod_id'],
            "marketable"    => $param['marketable'],
            "merchant_id"   => $this->config["merchant_id"],
        ];
        //组装推送上游数据
        $requestParam = [
            'method' => 'updateProdStatus',
            'data'   => $data,
        ];
        return $this->execute($requestParam);
    }

    /**
     * 签名
     * @param array $param
     */
    private function getSign($param = []) 
    {
        ksort($param);
        $arr = "";
        foreach ($param as $k => $v) {
            $arr .= "{$k}{$v}";
        }
        $AppSecret=$this->config["AppSecret"];
        $param["sign"] = strtoupper(md5($AppSecret.$arr.$AppSecret));
        return $param;
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute($param = []) 
    {
        $method                      = $param["method"];
        $url                         = $this->config["baseurl"].$this->routeMap[$method];
        $param["data"]["app_key"]    = $this->config["app_key"];
        $param["data"]["v"]          = $this->config["v"];
        $param["data"]["format"]     = "json";
        $param["data"]["timestamp"]  = time();
        $data                        = $this->getSign($param["data"]);
        $start                       = microtime(true);
        $response                    = Http::postFormUrlEncodedCurl($url, $data);
        $used_time                   = bcsub((string)microtime(true), $start,3);
        //写入日志
        MicroServiceLog::instance()->addLog([
            'interface_code'    => $this->account.'_'.$method,
            'request_url'       => $url,
            'request_param'     => json_encode($data,JSON_UNESCAPED_UNICODE),
            'response_code'     => 200,
            'response_data'     => $response,
            'req_used_time'     => $used_time,
        ]);
        $result   = @json_decode($response,true);
        if(!empty($result) && isset($result['ret']) && $result["ret"] == "0"){
            return Normal::returnCode(Normal::SUC,"处理成功",$result);
        }
        $result = empty($result) ? ['error'=>$response] : $result;
        $erroMsg = json_encode($result,JSON_UNESCAPED_UNICODE);
        return Normal::returnCode(Normal::FAIL,"处理失败【{$erroMsg}】",$result);
    }
}